package com.sl.au.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.sl.au.entity.Account;
import com.sl.au.entity.EventRegister;
import com.sl.au.entity.EventReport;
import com.sl.au.entity.EventToEvaluateUser;
import com.sl.au.entity.Option;
import com.sl.au.entity.User;
import com.sl.au.entity.EventProcessToEvaluateUser;
import com.sl.au.entity.VisitorReward;
import com.sl.au.entity.VisitorRewardProcessing;
import com.sl.au.service.EventRegisterService;
import com.sl.au.service.EventReportService;
import com.sl.au.service.EventToEvaluateUserService;
import com.sl.au.service.OptionService;
import com.sl.au.service.UserEventTypeBindInfoService;
import com.sl.au.service.UserService;
import com.sl.au.service.VisitorRewardProcessingService;
import com.sl.au.service.VisitorRewardService;
import com.sl.au.service.EventProcessToEvaluateUserService;
import com.sl.utils.ComparatorUtil;
import com.sl.utils.ExdeUtil;
import com.sl.utils.SHA256Util;

/**
 * personalType  1:游客;2:城管;3:领导;
 * @author yangdi
 *
 */

@RestController
@RequestMapping(value = "/ui/Personal") 
public class PersonalController  extends BaseController{
	
	@Autowired
	private EventRegisterService eventRegisterService;
	@Autowired
	private EventReportService eventReportService;
	@Autowired
	private OptionService optionService;
	@Autowired
	private VisitorRewardService visitorRewardService;
	@Autowired
	private EventToEvaluateUserService eventToEvaluateUserService;
	@Autowired
	private UserEventTypeBindInfoService userEventTypeBindInfoService;
	@Autowired
	private VisitorRewardProcessingService visitorRewardProcessingService;
	@Autowired
	private UserService userService;
	@Autowired
	private EventProcessToEvaluateUserService eventProcessToEvaluateUserService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAndView,HttpServletRequest request) {
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		String personalType = request.getParameter("type");
		if (StringUtils.hasText(device) && this.DEVICE.equals(device)) {
			modelAndView.setViewName("mobile/personal/personalIndex");
			modelAndView.addObject("identify", identify);
			modelAndView.addObject("account", this.getMyAccount());
			User user = userService.getRepository().findOne(this.getMyAccount().getUser().getId());
			modelAndView.addObject("userPic", user.getPictureAddress());
			modelAndView.addObject("personalType", personalType);
		}
		return modelAndView;
	}
	
	@RequestMapping(value = "getUser/{type}", method = RequestMethod.GET)
	public Map<String, Object> getUser(@PathVariable("type") String type) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();
		Account account = this.getMyAccount();
		User user = account.getUser();
		List<Option> options = new ArrayList<Option>();
		
		/*
		 * 查询个人积分及评分的时间周期
		 */
		Date begin = null;
		Date end = null;
		int offset = 0;
		/*
		 * 游客信息
		 */
		if(type.equals("1")) {
			//查询已上报条数
			int reportedCount = 0;
			reportedCount = eventReportService.getRepository().getCountByUser(user.getId());
			//待处理
			int pendingCount = 0;
			options.clear();
			options = optionService.getRepository().findByGroupAndTitle("事件上报状态", "初始化");
			if(options.size()>0) {
				pendingCount = eventReportService.getRepository().getCountByUserAndType(user.getId(), options.get(0).getId());
			}
			//已受理
			int admissibleCount = 0;
			options.clear();
			options = optionService.getRepository().findByGroupAndTitle("事件上报状态", "已受理");
			if(options.size()>0) {
				admissibleCount = eventReportService.getRepository().getCountByUserAndType(user.getId(), options.get(0).getId());
			}
			//已完结
			int completedCount = 0;
			options.clear();
			options = optionService.getRepository().findByGroupAndTitle("事件上报状态", "已完结");
			if(options.size()>0) {
				completedCount = eventReportService.getRepository().getCountByUserAndType(user.getId(), options.get(0).getId());
			}
			//已归档
			int archivCount = 0;
			options.clear();
			options = optionService.getRepository().findByGroupAndTitle("事件上报状态", "已归档");
			if(options.size()>0) {
				archivCount = eventReportService.getRepository().getCountByUserAndType(user.getId(), options.get(0).getId());
			}
			//个人积分
			double reward = 0;
/*
			options.clear();
			options = optionService.getRepository().findByGroupAndTitle("时间周期", "积分计算");
			if(options.size()>0) {
				Option option = options.get(0);
				offset = ExdeUtil.getCycDateOffset(option.getValue(),option.getExtended1());
				begin = ExdeUtil.getCycDate(option.getValue(),option.getExtended1(),offset);
				end = ExdeUtil.getCycDate(option.getValue(),option.getExtended1(),offset+1);
			}else {
				//默认为一个月
				offset = ExdeUtil.getCycDateOffset("month","1");
				begin = ExdeUtil.getCycDate("month","1",offset);
				end = ExdeUtil.getCycDate("month","1",offset+1);
			}
			reward = visitorRewardService.getUserRewardByDate(user.getId(), begin, end);
			List<VisitorReward> rewards = visitorRewardService.getRepository().getUserRewardListByDate(user.getId(), begin, end);
			
*/
			reward = visitorRewardProcessingService.getViewForVisitorRewardRepository().findOne(user.getId()).getTotalRewardValue();
			List rewards = visitorRewardService.getRepository().getUserRewardAll(user.getId());
			List rewardProcessings = visitorRewardProcessingService.getRepository().findAll();
			
			rewards.addAll(rewardProcessings);
			
			ComparatorUtil comparator=new ComparatorUtil(); 
	        Collections.sort(rewards, comparator.reversed()); 
			
			
			data.put("rewards", rewards);
/*			
			//已上报数据
			options.clear();
			options = this.optionService.getRepository().findByGroupAndTitle("事件上报状态", "初始化");
			if (options.size() > 0) {
				List<EventReport> reports = new ArrayList<EventReport>();
				reports = eventReportService.getReportPageByUserAndType(0, Integer.MAX_VALUE, user.getId(), options.get(0).getId(), "reportAccTime", Sort.Direction.DESC);
				data.put("reports", reports);
			}
			//已受理
			options.clear();
			options = this.optionService.getRepository().findByGroupAndTitle("事件上报状态", "已受理");
			if (options.size() > 0) {
				List<EventReport> deals = new ArrayList<EventReport>();
				deals = eventReportService.getReportPageByUserAndType(0, Integer.MAX_VALUE, user.getId(), options.get(0).getId(), "reportAccTime", Sort.Direction.DESC);
				data.put("deals", deals);
			}
			//已完成
			options.clear();
			options = this.optionService.getRepository().findByGroupAndTitle("事件上报状态", "已归档");
			if (options.size() > 0) {
				List<EventReport> finisheds = new ArrayList<EventReport>();
				finisheds = eventReportService.getReportPageByUserAndType(0, Integer.MAX_VALUE, user.getId(), options.get(0).getId(), "reportAccTime", Sort.Direction.DESC);
				data.put("finisheds", finisheds);
			}
*/			
			map.put("oneTitle", "上报历史");
			map.put("oneNum", reportedCount);
			map.put("twoTitle", "待处理");
			map.put("twoNum", pendingCount);
			map.put("threeTitle", "已受理");
			map.put("threeNum", admissibleCount);
			map.put("fourTitle", "已完结");
			map.put("fourNum", completedCount+archivCount);
			
			map.put("contentTitle", "个人积分");
			map.put("contentNum", reward);
		}else if(type.equals("2")) {
			/*
			 * 城管
			 */
			//查询已上报条数
			int reportedCount = 0;
			reportedCount = eventReportService.getRepository().getCountByUser(user.getId());
			//已接收数量
			int receiveNum = 0;
			List<EventRegister> receives = new ArrayList<EventRegister>();
			options = optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "处理中");
			if(options.size()>0) {
				receiveNum = eventRegisterService.getRepository().getRegisterCountByUserAndType(user.getId(),options.get(0).getId());
				//receives =  eventRegisterService.getRegisterUserAndType(0, Integer.MAX_VALUE, user.getId(), options.get(0).getId(), "createTime", Sort.Direction.DESC);
				//data.put("receives", receives);
			}
			
			//已完成数量
			int finishedNum = 0;
			options = optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "已完结");
			if(options.size()>0) {
				finishedNum = eventRegisterService.getRepository().getRegisterCountByUserAndType(user.getId(),options.get(0).getId());
			}
			
			double score = 0;
			options.clear();
			options = optionService.getRepository().findByGroupAndTitle("时间周期", "评分计算");
			if(options.size()>0) {
				Option option = options.get(0);
				offset = ExdeUtil.getCycDateOffset(option.getValue(),option.getExtended1());
				begin = ExdeUtil.getCycDate(option.getValue(),option.getExtended1(),offset);
				end = ExdeUtil.getCycDate(option.getValue(),option.getExtended1(),offset+1);
			}else {
				//默认为一个月
				offset = ExdeUtil.getCycDateOffset("month","1");
				begin = ExdeUtil.getCycDate("month","1",offset);
				end = ExdeUtil.getCycDate("month","1",offset+1);
			}
			score = eventToEvaluateUserService.getUserScoreByDate(user.getId(), begin, end);
			List<EventToEvaluateUser> scores = eventToEvaluateUserService.getRepository().getUserScoreListByDate(user.getId(), begin, end);
			List<EventProcessToEvaluateUser>scoresProcess =this.eventProcessToEvaluateUserService.getRepository().getUserProcessScoreListByDate(user.getId(), begin, end);
			data.put("scores", scores);
			data.put("scoresProcess", scoresProcess);
			map.put("oneTitle", "上报事件");
			map.put("oneNum", reportedCount);
			map.put("twoTitle", "接收任务");
			map.put("twoNum", receiveNum);
			map.put("threeTitle", "完成任务");
			map.put("threeNum", finishedNum);
			map.put("contentTitle", "个人评分");
			map.put("contentNum", score);
		}else if(type.equals("3")) {
			/*
			 * 领导
			 */
			//管辖事件
			int userEventTypeNum = 0;
			userEventTypeNum = userEventTypeBindInfoService.getRepository().getCountByUser(user.getId());
			//下属人员
			int subordinateNum = 0;
			//评分
			double score = 0;
			options.clear();
			options = optionService.getRepository().findByGroupAndTitle("时间周期", "评分计算");
			if(options.size()>0) {
				Option option = options.get(0);
				offset = ExdeUtil.getCycDateOffset(option.getValue(),option.getExtended1());
				begin = ExdeUtil.getCycDate(option.getValue(),option.getExtended1(),offset);
				end = ExdeUtil.getCycDate(option.getValue(),option.getExtended1(),offset+1);
			}else {
				//默认为一个月
				offset = ExdeUtil.getCycDateOffset("month","1");
				begin = ExdeUtil.getCycDate("month","1",offset);
				end = ExdeUtil.getCycDate("month","1",offset+1);
			}
			score = eventToEvaluateUserService.getUserScoreByDate(user.getId(), begin, end);
			
			//已上报数据
			options.clear();
			options = this.optionService.getRepository().findByGroupAndTitle("事件上报状态", "初始化");
			if (options.size() > 0) {
				List<EventReport> reports = new ArrayList<EventReport>();
				reports = eventReportService.getReportPageByUserAndType(0, Integer.MAX_VALUE, user.getId(), options.get(0).getId(), "reportAccTime", Sort.Direction.DESC);
				data.put("reports", reports);
			}
			//已受理
			options.clear();
			options = this.optionService.getRepository().findByGroupAndTitle("事件上报状态", "已受理");
			if (options.size() > 0) {
				List<EventReport> deals = new ArrayList<EventReport>();
				deals = eventReportService.getReportPageByUserAndType(0, Integer.MAX_VALUE, user.getId(), options.get(0).getId(), "reportAccTime", Sort.Direction.DESC);
				data.put("deals", deals);
			}
			//已完成
			options.clear();
			options = this.optionService.getRepository().findByGroupAndTitle("事件上报状态", "已归档");
			if (options.size() > 0) {
				List<EventReport> finisheds = new ArrayList<EventReport>();
				finisheds = eventReportService.getReportPageByUserAndType(0, Integer.MAX_VALUE, user.getId(), options.get(0).getId(), "reportAccTime", Sort.Direction.DESC);
				data.put("finisheds", finisheds);
			}
			
			map.put("oneTitle", "管辖事件");
			map.put("oneNum", userEventTypeNum);
			map.put("twoTitle", "下属人员");
			map.put("twoNum", subordinateNum);
			map.put("threeTitle", "个人评分");
			map.put("threeNum", score);
			
		}
		map.put("content", data);
		return map;
	}
	
	
	@RequestMapping(value="findEventReport/{id}",method = RequestMethod.GET)
	public Map<String, Object> findEventReport(@PathVariable("id") String id){
		Map<String, Object> map = new HashMap<String, Object>();
		EventReport eventReport = eventReportService.getRepository().findOne(id);
		map.put("eventReport", eventReport);
		return map;
	}
	
	@RequestMapping(value="findEventRegister/{id}",method = RequestMethod.GET)
	public Map<String, Object> findEventRegister(@PathVariable("id") String id){
		Map<String, Object> map = new HashMap<String, Object>();
		EventRegister eventRegister = eventRegisterService.getRepository().findOne(id);
		map.put("eventRegister", eventRegister);
		return map;
	}
	
	@RequestMapping(value = "saveUserPic/{userId}", method = RequestMethod.POST)
	public Map<String, Object> saveUserPic(@RequestParam(value = "picfile", required = false) MultipartFile file,@PathVariable("userId") String userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		User user = userService.getRepository().findOne(userId);
		
		String url = "";
		if (file!=null) {
			if (file.getOriginalFilename() != null && !"".equals(file.getOriginalFilename())) {
				// 注意路径的构建
				url = getUploadFilePath(this.fileUploadPath, "UserPic", file);
			}else{
				url=user.getPictureAddress();
			}
		}
		
		
		user.setPictureAddress(url);
		String password = request.getParameter("password");
		if (password!=null&&!"".equals(password)) {//更改密码及头像
			Account account = accountService.getRepository().findByUser(user);
			account.setPassword(SHA256Util.getSHA256StrJava(password));
			account.setMemo(password);
			accountService.saveAll(account,user);
		}else{//不更改密码
			userService.getRepository().save(user);
		}
		
		map.put("code", 1);
		map.put("userPic", url);
		return map;
	}
}
